//
//  DriverViewController.m
//  
//
//  Created by chenxu on 15/3/8.
//
//

#import "DriverViewController.h"
#import "exampleViewController.h"
#import "InsurancesViewController.h"
#import "ConversationViewController.h"
#import "NetAPIManager.h"
#import "OrderlistViewController.h"
#import "Recomend_Cell.h"
@implementation DriverViewController


- (void)viewDidLoad{
    [super viewDidLoad];
    [self.view bringSubviewToFront:_recommend];
    _getPriceBtn.layer.cornerRadius = kCornerRadius;
    _sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:nil];
    _insuranceInfo = [NSObject loadPlist:@"insuranceinfo"];
    _driversInfo = [NSObject loadPlist:@"drivers"];
    NSDictionary* driver = [_driversInfo objectForKey:_driver];
    
    if (_driver) {
        self.title = [driver objectForKey:@"title"];
        _ins = [[Insurances alloc]initWithDriver:_driver];
        _me.text = [driver objectForKey:@"title"];
        _slogan.text = [driver objectForKey:@"slogan"];
        _mysentence.text = [driver objectForKey:@"mysentence"];
        _mysentence.textColor = [UIColor whiteColor];
        _expertsentence.text = [driver objectForKey:@"expertsentence"];
        _myimg.image = [[UIImage imageNamed:@"用户输入框"] resizableImageWithCapInsets:UIEdgeInsetsMake(15, 50, 10, 10)];
        _expertimg.image = [[UIImage imageNamed:@"专家输入框"] resizableImageWithCapInsets:UIEdgeInsetsMake(15, 10, 10, 70)];
     
        NSString* avatar = [[NSString alloc]initWithFormat:@"avatar_%@",_driver];
        _avatar.image = [UIImage imageNamed:avatar];
        [_getPriceBtn setPopingPressed];
    }
    _tablebackground.layer.cornerRadius = kCornerRadius;
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    _carid.text = [Login curCarid];
    [_insurances reloadData];
    
}

- (NSDictionary *)toPriceParams{
    if (_companyinfo.text && ![_companyinfo.text isEqualToString:@"车险公司"] ) {
        
        return @{
                 @"Username" : [Login curLoginUser].Username,
                 @"Uid"      : [Login curLoginUser].Uid,
                 @"Cid"      : [Login curCid],
                 @"Company"  : _companyinfo.text,
                 @"Xianzhong": [_ins toJsonString]
                 };
        
    }
    else
    {
        return nil;
    }
   
}

- (IBAction)getPrice:(id)sender {
    //尚未登录
    if (![Login isLogin]) {
        [self performSegueWithIdentifier:@"loginFromDriver" sender:self];
        [self showHudTipStr:@"尚未登录"];
    }
    //已经登陆
    else{
        if ([self toPriceParams]) {
            
            
            [[NetAPIManager sharedManager]request_price:[self toPriceParams] andBlock:^(id data, NSError *error) {
                
                if (data) {
                    [self showHudTipStr:@"订单生成成功"];
                    NSString* orderid = [data valueForKey:@"Orderid"];
                    
                    
                    [[NetAPIManager sharedManager] request_unfinishedorder:[[Login curLoginUser] toUsernameParams] andBlock:^(id data, NSError *error) {
                        if (data) {
                            NSArray* datalist = [[NSArray alloc]initWithArray:data];
                            for (int i=0; i< [datalist count]; i++) {
                
                                Order* order = [NSObject objectOfClass:@"Order" fromJSON:[datalist objectAtIndex:i]];
                                
                                //在未完成订单中找到这个订单
                                if ([order.Orderid isEqualToString:orderid]) {
                                    [self performSegueWithIdentifier:@"neworder" sender:order];
                                }
                            }
                            
                        }
                    }];
                }
                
            }];
        }
        else{
            [self showHudTipStr:@"请选择保险公司和车辆"];
        }
    }
}


- (IBAction)switchview:(id)sender {
    UISegmentedControl *segmentedControl = sender;
    NSInteger index = [segmentedControl selectedSegmentIndex];
    if(index==0){
        [self.view bringSubviewToFront:_recommend];
    }
    else if(index==1){
        [self.view bringSubviewToFront:_analysis];
    }
}

#pragma mark - table view
#pragma mark Table Data Source Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    [tableView registerClass:[Recomend_Cell class] forCellReuseIdentifier:@"insurance"];

    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_ins getlist].count;
}
#pragma mark Table Delegate Methods
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *CellIdentifier = @"insurance";
    Recomend_Cell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    NSString *index = [[_ins getlist] objectAtIndex:indexPath.row];
    NSString *title = [[_insuranceInfo objectForKey:index]objectForKey:@"name"];
    
    
//    if ([index isEqualToString:@"2"]){
//        title = [title stringByAppendingString:[_ins getThird]];
//    }
    title = [[NSString alloc]initWithFormat:@"%@.%@",index,title];
    
    [cell setTitle:title];
  
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self performSegueWithIdentifier:@"showintro" sender:indexPath];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    NSString* kind = segue.identifier;
   
    if ([kind isEqualToString:@"showintro"]) {
        exampleViewController* nextView = [segue destinationViewController];
        NSInteger row = [(NSIndexPath*)sender row];
        NSString *index = [[_ins getlist] objectAtIndex:row];
        [nextView setIndex:index];
    }
    else if ([kind isEqualToString:@"neworder"]){
        ConversationViewController* vc = [segue destinationViewController];
        vc.myOrder = (Order*)sender;
    }
    else if ([kind isEqualToString:@"makePrefer"]){
        InsurancesViewController* insview = [segue destinationViewController];
        insview.ins = _ins;
    }
}


#pragma mark - picker view
#pragma mark Actionsheet delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    companyIndex = buttonIndex-1;
    //排除-1为取消按钮
    if (companyIndex >= 0) {
        _companyinfo.text = [[_companies objectAtIndex:companyIndex]objectForKey:@"Company"];

    }
}

/*!
 *  @brief  点击车险公司按钮，触发：获取公司列表，成功后用actionsheet显示
 *  @param sender 车险公司按钮
 */
- (IBAction)selectcompany:(id)sender {
    [[NetAPIManager sharedManager] request_company:nil andBlock:^(id data, NSError *error) {
        if (data) {
            _companies = data;
            for (int i=0; i<[_companies count]; i++) {
                NSString* title = [[_companies objectAtIndex:i]objectForKey:@"Company"];
                [_sheet addButtonWithTitle:title];
            }
            [_sheet showInView:_analysis];
        }else{
            
        }
    }];
}

- (IBAction)selectcar:(id)sender {
    if (![Login isLogin]) {
        [self performSegueWithIdentifier:@"loginFromDriver" sender:self];
    }
}

- (void)loadlabels{
    
}
@end
